<template>
    <div class="roster-page">
        <!-- 頁面標題 -->
        <page-title :title="'花名冊管理'" />

        <!-- 篩選條件區域 -->
        <div class="filter-section">
            <el-form :model="filterForm" label-width="80px" label-position="left">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="職位">
                            <el-select v-model="filterForm.position" placeholder="請選擇職位" clearable>
                                <el-option v-for="item in positionOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="職務">
                            <el-select v-model="filterForm.job" placeholder="請選擇職務" clearable>
                                <el-option v-for="item in jobOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="職級">
                            <el-select v-model="filterForm.rank" placeholder="請選擇職級" clearable>
                                <el-option v-for="item in rankOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="部門">
                            <el-select v-model="filterForm.department" placeholder="請選擇部門" clearable>
                                <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="工作地點">
                            <el-select v-model="filterForm.location" placeholder="請選擇工作地點" clearable>
                                <el-option v-for="item in locationOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="選擇日期">
                            <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                                start-placeholder="開始日期" end-placeholder="結束日期" value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="關鍵字搜索">
                            <el-input v-model="filterForm.keyword" placeholder="請輸入員工姓名/工號/手機號碼" clearable
                                @clear="handleSearch" @keyup.enter="handleSearch">
                                <template #append>
                                    <el-button type="primary" @click="handleSearch">
                                        <el-icon>
                                            <Search />
                                        </el-icon>
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 操作按鈕區域 -->
        <div class="action-section">
            <el-button type="primary" @click="addEmployee">
                <el-icon>
                    <Plus />
                </el-icon>
                <span>新增員工</span>
            </el-button>
            <el-button type="success" @click="importEmployees">
                <el-icon>
                    <Upload />
                </el-icon>
                <span>導入</span>
            </el-button>
            <el-button type="warning" @click="exportEmployees">
                <el-icon>
                    <Download />
                </el-icon>
                <span>導出</span>
            </el-button>
            <el-dropdown @command="handleMoreAction">
                <el-button type="info">
                    <span>更多操作</span>
                    <el-icon class="el-icon--right">
                        <ArrowDown />
                    </el-icon>
                </el-button>
                <template #dropdown>
                    <el-dropdown-menu>
                        <el-dropdown-item command="sendForm">發送入職登記表</el-dropdown-item>
                        <el-dropdown-item command="startApproval">發起審批</el-dropdown-item>
                        <el-dropdown-item command="delete" divided>刪除</el-dropdown-item>
                    </el-dropdown-menu>
                </template>
            </el-dropdown>
        </div>

        <!-- 狀態卡片區域 -->
        <div class="status-cards-section">
            <el-row :gutter="24" style="display: flex;justify-content: space-between;">
                <div v-for="status in employeeStatus" :key="status.value" class="status-card"
                    :class="{ active: activeStatus === status.value }" @click="changeStatus(status.value)">
                    <div class="status-name">{{ status.label }}</div>
                    <div class="status-count">
                        <vue-countup-v3 :endVal="status.count" :options="countUpOptions" />
                    </div>
                </div>
            </el-row>
        </div>

        <!-- 員工表格區域 -->
        <div class="employee-table-section">
            <el-table :data="employeeList" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="員工姓名" width="120" />
                <el-table-column prop="employeeId" label="工號" width="120" />
                <el-table-column prop="department" label="部門" width="150" />
                <el-table-column prop="phone" label="手機號碼" width="150" />
                <el-table-column prop="position" label="職位" width="150" />
                <el-table-column prop="type" label="類型" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getTagType(row.type)">{{ row.type }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="idNumber" label="證件號" width="180" />
                <el-table-column prop="entryDate" label="入職時間" width="150" />
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="viewDetails(row)">
                            查看詳情
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分頁 -->
            <div class="pagination-section">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 新增員工對話框 -->
        <el-dialog v-model="addDialogVisible" :title="'新增員工'" width="600px">
            <employee-form ref="employeeForm" @submit="handleAddSubmit" />
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitAddForm">確定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Plus, Upload, Download, ArrowDown } from '@element-plus/icons-vue'
import VueCountupV3 from 'vue-countup-v3'
import PageTitle from '@/components/pageTitle/pageTitle.vue'
// import EmployeeForm from './components/EmployeeForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 篩選表單
const filterForm = reactive({
    position: '',
    job: '',
    rank: '',
    department: '',
    location: '',
    dateRange: [],
    keyword: ''
})

// 下拉選項
const positionOptions = [
    { value: 'manager', label: '經理' },
    { value: 'developer', label: '開發人員' },
    { value: 'designer', label: '設計師' }
]
const jobOptions = [
    { value: 'dev', label: '開發' },
    { value: 'test', label: '測試' },
    { value: 'product', label: '產品' }
]
const rankOptions = [
    { value: 'p1', label: 'P1' },
    { value: 'p2', label: 'P2' },
    { value: 'p3', label: 'P3' }
]
const departmentOptions = [
    { value: 'rd', label: '研發部' },
    { value: 'hr', label: '人事部' },
    { value: 'finance', label: '財務部' }
]
const locationOptions = [
    { value: 'shanghai', label: '上海' },
    { value: 'beijing', label: '北京' },
    { value: 'guangzhou', label: '廣州' }
]

// 員工狀態卡片
const activeStatus = ref('all')
const employeeStatus = ref([
    { value: 'all', label: '全部', count: 125 },
    { value: 'onJob', label: '在職', count: 85 },
    { value: 'probation', label: '試用', count: 15 },
    { value: 'formal', label: '正式', count: 70 },
    { value: 'pendingLeave', label: '待離職', count: 5 },
    { value: 'left', label: '已離職', count: 20 },
    { value: 'pendingEntry', label: '待入職', count: 5 }
])

// CountUp 配置
const countUpOptions = {
    duration: 1,
    decimalPlaces: 0,
    separator: ','
}

// 員工表格數據
const loading = ref(false)
const employeeList = ref([
    {
        id: 1,
        name: '張三',
        employeeId: '10001',
        department: '研發部',
        phone: '13800138000',
        position: '前端開發',
        type: '正式',
        idNumber: '310************012',
        entryDate: '2020-05-15'
    },
    {
        id: 2,
        name: '李四',
        employeeId: '10002',
        department: '研發部',
        phone: '13800138001',
        position: '後端開發',
        type: '試用',
        idNumber: '310************013',
        entryDate: '2023-01-10'
    }
])

// 分頁
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 2
})

// 多選
const selectedEmployees = ref([])

// 新增員工對話框
const addDialogVisible = ref(false)
// const employeeForm = ref(null)

// 方法
const handleSearch = () => {
    loading.value = true
    // 模擬API請求
    setTimeout(() => {
        loading.value = false
    }, 500)
}

const addEmployee = () => {
    addDialogVisible.value = true
}

const importEmployees = () => {
    ElMessage.info('導入功能待實現')
}

const exportEmployees = () => {
    ElMessage.info('導出功能待實現')
}

const handleMoreAction = (command) => {
    if (selectedEmployees.value.length === 0) {
        ElMessage.warning('請至少選擇一個員工')
        return
    }

    switch (command) {
        case 'sendForm':
            ElMessage.info(`將向 ${selectedEmployees.value.length} 位員工發送入職登記表`)
            break
        case 'startApproval':
            ElMessage.info(`將為 ${selectedEmployees.value.length} 位員工發起審批`)
            break
        case 'delete':
            deleteEmployees()
            break
    }
}

const deleteEmployees = () => {
    ElMessageBox.confirm(
        `確定要刪除選中的 ${selectedEmployees.value.length} 位員工嗎？`,
        '提示',
        {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        ElMessage.success('刪除成功')
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const changeStatus = (status) => {
    activeStatus.value = status
    // 根據狀態篩選數據
    handleSearch()
}

const handleSelectionChange = (selection) => {
    selectedEmployees.value = selection
}

const handleSizeChange = (val) => {
    pagination.pageSize = val
    handleSearch()
}

const handleCurrentChange = (val) => {
    pagination.currentPage = val
    handleSearch()
}

const viewDetails = (row) => {
    ElMessage.info(`查看 ${row.name} 的詳情`)
}

// const submitAddForm = () => {
//     employeeForm.value.submitForm()
// }

const handleAddSubmit = (formData) => {
    // 模擬新增員工
    employeeList.value.unshift({
        id: employeeList.value.length + 1,
        ...formData
    })
    addDialogVisible.value = false
    ElMessage.success('新增員工成功')
}

const getTagType = (type) => {
    switch (type) {
        case '正式': return 'success'
        case '試用': return 'warning'
        case '待離職': return 'danger'
        case '已離職': return 'info'
        case '待入職': return ''
        default: return ''
    }
}

onMounted(() => {
    handleSearch()
})
</script>

<style lang="less" scoped>
.roster-page {
    padding: 20px;
    background-color: #fff;

    .filter-section {
        padding: 16px;
        margin-bottom: 16px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    }

    .action-section {
        margin-bottom: 16px;
        display: flex;
        gap: 12px;
        justify-content: end;
    }

    .status-cards-section {
        margin-bottom: 20px;

        .status-card {
            padding: 16px;
            background-color: #fff;
            border-radius: 4px;
            box-shadow: rgba(14, 63, 126, 0.06) 0px 0px 0px 1px, rgba(42, 51, 70, 0.03) 0px 1px 1px -0.5px, rgba(42, 51, 70, 0.04) 0px 2px 2px -1px, rgba(42, 51, 70, 0.04) 0px 3px 3px -1.5px, rgba(42, 51, 70, 0.03) 0px 5px 5px -2.5px, rgba(42, 51, 70, 0.03) 0px 10px 10px -5px, rgba(42, 51, 70, 0.03) 0px 24px 24px -8px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
            width: 160px;

            &:hover {
                transform: translateY(-3px);
                box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
            }

            &.active {
                background-color: var(--el-color-primary-light-9);
                border: 1px solid var(--el-color-primary);
            }

            .status-name {
                font-size: 14px;
                color: var(--el-text-color-regular);
                margin-bottom: 8px;
            }

            .status-count {
                font-size: 20px;
                font-weight: bold;
                color: var(--el-color-primary);
            }
        }
    }

    .employee-table-section {
        background-color: #fff;
        padding: 16px;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

        .pagination-section {
            margin-top: 16px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>